<template>
  <section>
    <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="自营商品" name="0"></el-tab-pane>
      <el-tab-pane label="分销商品" name="1"></el-tab-pane>
    </el-tabs>
    <div class="filter-container">
        <common-input @keyup.enter.native="handleFilter" class="w200" placeholder="专场关键字" v-model="listQuery.keyword" />
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
            <el-button size="mini" class="ml10" @click="handleCreate" type="primary" icon="el-icon-plus">新增</el-button>
    </div>
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                style="width: 100%">
            <el-table-column align="left" label="专场ID">
                <template slot-scope="scope">
                    <span>{{scope.row.id}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="专场名称">
                <template slot-scope="scope">
                    <span>{{scope.row.title}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="副标题">
                <template slot-scope="scope">
                    <span>{{scope.row.subTitle}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="有效时间">
                <template slot-scope="scope">
                    {{scope.row.startDate}}-{{scope.row.endDate}}
                </template>
            </el-table-column>
            <el-table-column width="150" align="right" label="关联商品数">
                <template slot-scope="scope">
                    <span>{{scope.row.productNum}}</span>
                </template>
            </el-table-column>

            <el-table-column label="首页展示">
                <template slot-scope="scope">
                <el-switch
                    :key="scope.row.id"
                    :active-value="1"
                    :inactive-value="0"
                    :value="scope.row.type"
                    @change="isUseActivityChange(scope.row.id,$event)"
                ></el-switch>
                <!-- <span v-else>已禁用</span> -->
                </template>
            </el-table-column>
            <el-table-column label="标签展示">
                <template slot-scope="scope">
                <el-switch
                    :key="scope.row.id"
                    :active-value="1"
                    :inactive-value="0"
                    :value="scope.row.inTab"
                    @change="isUseInTabChange(scope.row.id,$event)"
                ></el-switch>
                <!-- <span v-else>已禁用</span> -->
                </template>
            </el-table-column>
            <el-table-column label="会员中心展示">
                <template slot-scope="scope">
                <el-switch
                    :key="scope.row.id"
                    :active-value="1"
                    :inactive-value="0"
                    :value="scope.row.inMine"
                    @change="isUseInMineChange(scope.row.id,$event)"
                ></el-switch>
                <!-- <span v-else>已禁用</span> -->
                </template>
            </el-table-column>
            <el-table-column align="right" width="80" label="排序">
                <template slot-scope="scope">
                    <span>{{scope.row.sort}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" 
                    fixed="right">
                <template slot-scope="scope">
                    <span>
                        <el-button type="text" @click="handleRelate(scope.row)">关联商品</el-button>
                        <el-dropdown class="ml10">
                        <el-button

                                type="text">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item  @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="700px">
        <el-form :model="form" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="专场名称" prop="title">
                <common-input v-model="form.title" placeholder="请输入专场名称" maxlength="10" />
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle">
                <common-input v-model="form.subTitle" placeholder="请输入专场副标题" maxlength="10" />
            </el-form-item>
            <el-form-item label="专场首页图片" prop="banner">
                <pic-sel style="float:left" v-model="form.banner" />
                <p>首页专场模块内banner图，推荐宽高710*184px</p>
            </el-form-item>
            <el-form-item label="专场标题图片" prop="bannerTitle">
                <pic-sel style="float:left" v-model="form.bannerTitle" />
            </el-form-item>
            <el-form-item label="专场背景色" prop="bgColor">
                <common-input v-model="form.bgColor" placeholder="" maxlength="10" />
            </el-form-item>
            <el-form-item label="专场文字样式" prop="isLight">
                <el-radio-group v-model="form.isLight">
                    <el-radio :label="0">深色</el-radio>
                    <el-radio :label="1">浅色</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="首页banner链接" prop="bannerProduct">
                <common-input v-model="form.bannerProduct" placeholder="" />
                <p>首页专场模块内banner图跳转链接，为空时跳转专题列表页</p>
            </el-form-item>
            <el-form-item label="专场列表图片" prop="listBanner">
                <pic-sel style="float:left" v-model="form.listBanner" />
                <p>专题列表页顶部大图，高度不限</p>
            </el-form-item>
            <el-form-item label="列表banner链接" prop="listBannerProduct">
                <common-input v-model="form.listBannerProduct" placeholder="" />
                <p>专场列表内banner图跳转链接，为空时不跳转</p>
            </el-form-item>
            <el-form-item label="有效时间" prop="startDate">
                <el-date-picker
                    size="mini"
                    value-format="yyyy-MM-dd"
                    v-model="dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="专场排序" prop="sort">
                <common-input v-model="form.sort" class="w60" maxlength="3" />
            </el-form-item>
            <el-form-item label="分享描述" prop="shareDescribe">
                <common-input v-model="form.shareDescribe" placeholder="请输入分享描述" maxlength="24" />
                <p>分享描述不超过24个字</p>
            </el-form-item>
            <el-form-item label="分享图片" prop="sharePic">
                <pic-sel style="float:left" v-model="form.sharePic" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible=false">取消</el-button>
            <el-button size="mini" v-if="dialogStatus=='create'" type="primary" @click="create('form')">确定</el-button>
            <el-button size="mini" v-else type="primary" @click="update('form')">确定</el-button>
        </div>
    </el-dialog>
  </section>
</template>

<script>
    import {
        isIntegerNotMust
    } from '../../utils/validator'
    import {
        product_page_list,
        product_page_delete,
        product_page_save,
        product_page_detail,
        product_page_switch,
        product_page_in_tab,
        product_page_in_mine,
    } from '../../api/product';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
            'pic-sel': () => import('../../components/PicSel/index')
        },
        data() {
            return {
                activeName: '0',
                rules: {
                    title: [
                        {
                            required: true,
                            message: '请输入专场名称',
                            trigger: 'blur'
                        }
                    ],
                    // banner: [
                    //     {
                    //         required: true,
                    //         message: '请选择专场图片',
                    //         trigger: 'blur'
                    //     }
                    // ],
                    // listBanner: [
                    //     {
                    //         required: true,
                    //         message: '请选择专场列表图片',
                    //         trigger: 'blur'
                    //     }
                    // ],
                    orderid: [
                        {
                            validator: isIntegerNotMust,
                            trigger: 'blur'
                        }
                    ]
                },
                dateRange: undefined,
                dialogStatus: '',
                dialogFormVisible: false,
                textMap: {
                    update: '编辑专场',
                    create: '新增专场'
                },
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                cateList: [],
                parentCateList:[],
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: 1,
                    pageSize: 20,
                    agency: undefined,
                    keyword: undefined,
                    auditStatus: '3',
                    orderCol: "",
                    orderAsc: "",
                    cateId: undefined,
                    parentCateId: undefined,
                    status: '1',
                    getSaleCount: 1,
                    isRetail: 0,
                },
                form: {
                    id: undefined,
                    title: undefined,
                    banner: undefined,
                    bannerProduct: undefined,
                    listBanner: undefined,
                    listBannerProduct: undefined,
                    startDate: undefined,
                    endDate: undefined,
                    sort: undefined,
                    shareDescribe: undefined,
                    sharePic: undefined,
                    subTitle: undefined,
                    bannerTitle: undefined,
                    isRetail: 0,
                    bgColor: undefined,
                    isLight: "0",
                },
                total: null,
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getList();
        },
        methods: {
            handleClick(tab, event) {
                this.listQuery.isRetail = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            isUseActivityChange(id, e) {
                product_page_switch(id).then((res)=>{
                    this.getList();
                    this.$message.success("专场状态切换成功");
                }).catch((err)=>{

                })
            },
            isUseInTabChange(id, e) {
                product_page_in_tab(id).then((res)=>{
                    this.getList();
                    this.$message.success("专场状态切换成功");
                }).catch((err)=>{

                })
            },
            isUseInMineChange(id, e) {
                product_page_in_mine(id).then((res)=>{
                    this.getList();
                    this.$message.success("专场状态切换成功");
                }).catch((err)=>{

                })
            },
            create(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.sort) {
                            this.form.sort = 0;
                        }
                        if(!this.form.sort) {
                            this.form.sort = 0;
                        }
                        let start_date = '';
                        let end_date = '';
                        if(this.dateRange) {
                            start_date = this.dateRange[0];
                            end_date = this.dateRange[1];
                        }
                        this.form.startDate = start_date;
                        this.form.endDate = end_date;
                        product_page_save(this.form)
                            .then(() => {
                                this.dialogFormVisible = false;
                                this.getList();
                                this.$message.success("专场创建成功");
                            })
                    } else {
                        return false;
                    }
                });
            },
            update(formName) {
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        if(!this.form.sort) {
                            this.form.sort = 0;
                        }
                        let start_date = '';
                        let end_date = '';
                        if(this.dateRange) {
                            start_date = this.dateRange[0];
                            end_date = this.dateRange[1];
                        }
                        this.form.startDate = start_date;
                        this.form.endDate = end_date;
                        this.form.password = undefined;
                        product_page_save(this.form).then(() => {
                            this.dialogFormVisible = false;
                            this.getList();
                            this.$message.success("专场更新成功");
                        });
                    } else {
                        return false;
                    }
                });
            },
            resetTemp() {
                this.form = {
                    id: undefined,
                    title: undefined,
                    banner: undefined,
                    bannerProduct: undefined,
                    listBanner: undefined,
                    listBannerProduct: undefined,
                    startDate: undefined,
                    endDate: undefined,
                    sort: undefined,
                    shareDescribe: undefined,
                    sharePic: undefined,
                    isRetail: this.listQuery.isRetail,
                    bgColor: undefined,
                    isLight: 0,
                };
            },
            handleCreate() {
                this.resetTemp();
                this.dialogStatus = 'create';
                this.dialogFormVisible = true;
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                product_page_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            viewPic(row) {
                if(row.imgUrls) {
                    let all_pic = row.imgUrls.split(",");
                    $("#pic_viewer").html("");
                    if(all_pic && all_pic.length > 0) {
                        all_pic.forEach((item, idx)=>{
                            var str  = '<li style="width:100%;">';
                            str += '<img rel-src="' + item + '" src="' + item + '">';
                            str += '</li>';
                            $("#pic_viewer").append(str);
                        })
                    }
                    this.viewerId && this.viewerId.destroy()
                    this.viewerId = new Viewer(document.getElementById('pic_viewer'));
                    $('#pic_viewer').find("img").eq(0).trigger("click")
                }
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleUpdate(row) {
                product_page_detail(row.id)
                    .then(response => {
                        this.form = response.data;
                        if(this.form.startDate && this.form.endDate) {
                            this.dateRange  =[this.form.startDate, this.form.endDate]
                        }
                        this.dialogFormVisible = true;
                        this.dialogStatus = 'update';
                    });
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        product_page_delete(row.id)
                            .then(() => {
                                this.$message.success("专场删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            handleRelate(row) {
                if(row.isRetail == 1) {
                    this.$router.push("/retail_goods_page_relate_list?id=" + row.id + "&from=" + encodeURIComponent(this.$router.currentRoute.name)) 

                } else {
                    this.$router.push("/goods_page_relate_list?id=" + row.id + "&from=" + encodeURIComponent(this.$router.currentRoute.name)) 

                }
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
